package com.sos.dao;

import java.util.ArrayList;

import com.sos.vo.Contactor;


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
/****
 * 
 * 通讯录操作类
 * */
public class ContactorDao {
	private final String TAG = ContactorDao.class.getSimpleName();
	
	private DatabaseHelper dbHelper;
    private SQLiteDatabase db;
    private String TABLE = "contactor";
    
    /**
     * 构造函数
     * @param context
     */
	public ContactorDao(Context context){
		dbHelper = new DatabaseHelper(context);
    }
	
	/**
	 * 创建
	 * @param bean
	 * @return
	 */
	public void create(Contactor bean){
		Log.i(TAG, "create");
    	
    	ContentValues values = new ContentValues();
		values.put("name", bean.getName());
		values.put("phone", bean.getPhone());
		values.put("type", new Integer(bean.getType()));
		
		db = dbHelper.getWritableDatabase();
		db.insert(TABLE, null, values);
		db.close();
    }
	
	/**
	 * 删除
	 * @param id
	 * @return
	 */
	public void delete(int id){
		Log.i(TAG, "delete");
		String where = "id=?";
		String[] whereArgs = {String.valueOf(id)};
		
		db = dbHelper.getWritableDatabase();
		db.delete(TABLE, where, whereArgs);
		db.close();
    }
    
    /**
     * 获取所有列表
     */
    public ArrayList<Contactor> getList(int type){
		Log.i(TAG, "getList");
    	ArrayList<Contactor> list = new ArrayList<Contactor>();
    	
    	db = dbHelper.getReadableDatabase();
		String[] columns = new String[] {"id", "name", "phone"};
		String where = "type=?";
		String[] whereArgs = {String.valueOf(type)};
		
		Cursor cursor = db.query(true, TABLE, columns, where, whereArgs, null, null, null, null);
		while (cursor.moveToNext()) {
			Contactor bean = new Contactor();
			bean.setId(cursor.getInt(0));
			bean.setName(cursor.getString(1));
			bean.setPhone(cursor.getString(2));
			bean.setType(type);
			list.add(bean);
			
			Log.d(TAG, "id:" + bean.getId());
			Log.d(TAG, "name:"+bean.getName());
			Log.d(TAG, "phone:"+bean.getPhone());
			Log.d(TAG, "type:"+bean.getType());
		}
		cursor.close();
		db.close();
		
		return list;
    }
    
    /**
     * 获取记录数
     */
    public int getCount(){
		Log.i(TAG, "getCount");
    	int count = 0;
    	
    	db = dbHelper.getReadableDatabase();
		String[] columns = new String[] {"id"};
		
		Cursor cursor = db.query(true, TABLE, columns, null, null, null, null, null, null);
		if (cursor != null) {
			try {
				count = cursor.getCount();
			} finally {
				cursor.close();
			}
		}
		db.close();
		
		return count;
    }
}
